package com.tql.mall.merchant.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tql.mall.common.result.R;
import com.tql.mall.merchant.service.LogisInfoService;
import com.tql.mall.merchant.service.StockInfoService;
import com.tql.mall.model.enums.OrderStatus;
import com.tql.mall.model.merchant.LogisInfo;
import com.tql.mall.model.merchant.StockInfo;
import com.tql.mall.model.order.OrderDetail;
import com.tql.mall.model.order.OrderInfo;
import com.tql.mall.order.client.OrderFeignClient;
import io.swagger.annotations.Api;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/merchant/stock")
@Api("库存信息相关接口")
public class StockInfoController {

    @Autowired
    private OrderFeignClient orderFeignClient;

    @Autowired
    private StockInfoService stockInfoService;

    @Autowired
    private LogisInfoService logisInfoService;

    /**
     * 订单发货后，需要：1.更新库存  2.更新订单状态  3.生成运单
     * @return
     */
    @PostMapping ("updateStock")
    public R<Void> updateStock(@RequestBody OrderInfo orderInfo){
        OrderDetail orderDetail = orderInfo.getOrderDetailList().get(0);
        //更新库存
        QueryWrapper<StockInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("sku_id",orderDetail.getSkuId());
        StockInfo stockInfo = stockInfoService.getOne(wrapper);
        stockInfo.setNum(stockInfo.getNum() - orderDetail.getSkuNum());
        stockInfoService.updateById(stockInfo);

        //生成运单
        LogisInfo logisInfo = new LogisInfo();
        BeanUtils.copyProperties(orderInfo,logisInfo);
        logisInfo.setOrderStatus(OrderStatus.WAIT_DELIVER.name());
        logisInfo.setId(null);
        logisInfo.setOrderId(orderInfo.getId());
        logisInfo.setCreateTime(null);
        logisInfo.setUpdateTime(null);
        logisInfo.setShopId(orderInfo.getShopId());

        logisInfoService.addLogis(logisInfo);
        return R.ok();
    }
}
